<?php

namespace common\models\user;

use Yii;
use common\models\member\Member;
use common\models\member\MemberMarketLog;

/**
 * This is the model class for table "{{%user_branch}}".
 *
 * @property int $id
 * @property int $user_id 用户ID
 * @property int $member_id 上级会员ID
 * @property int $member_user_id 上级用户ID
 * @property int $status 成员状态：-1协议终止，0未确认，10已确认
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 * @property int $deleted_at 脱离时间
 */
class UserBranch extends \common\db\ActiveRecord {

    use \common\traits\relation\UserData;

    const STATUS_ACTIVE = 10;
    const STATUS_DEFAULT = 0;

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%user_branch}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['user_id', 'member_id', 'member_user_id', 'status', 'created_at', 'updated_at', 'deleted_at'], 'integer'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'user_id' => '用户ID',
            'member_id' => '上级会员ID',
            'member_user_id' => '上级用户ID',
            'status' => '成员状态：-1协议终止，0未确认，10已确认',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
            'deleted_at' => '脱离时间',
        ];
    }

    /**
     * 获取用户分支
     * {@inheritdoc}
     */
    public static function findByUserId($userid) {
        $query = static::findActive('t', static::STATUS_ACTIVE)->andWhere([
            't.user_id' => $userid,
        ]);
//        $query->innerJoinWith('member m');
//        $query->andWhere([
//            'm.deleted_at' => 0,
//            'm.status' => Member::STATUS_ACTIVE,
//        ]);
        $query->innerJoinWith([
            'member m' => function ($q) {
                $q->active(Member::STATUS_ACTIVE);
            }
        ]);
        Yii::error($query->debug());
        return $query->one();
    }

    /**
     * 获取用户关联会员模型记录
     * {@inheritdoc}
     */
    public static function findMemberByUserId($userid) {
        $model = static::findByUserId($userid);
        if (!$model) {
            return null;
        }
        return $model->member;
    }

    /**
     * 获取用户上层分支
     * {@inheritdoc}
     */
    public function getMember() {
        return $this->hasOne(\common\models\member\Member::class, ['id' => 'member_id']);
    }

    /**
     * 获取用户上层分支
     * {@inheritdoc}
     */
    public function getUpper() {
        return $this->hasOne(\common\models\member\Member::class, ['id' => 'member_id']);
    }

    public function getCustomerService() {
        $reg = $this->user_id;
        $cmd = $this->getDb()->createCommand("select findCustomerServiceList(:uid)");
        $cmd->bindParam(':uid', $reg, \PDO::PARAM_STR, 100);
        $list = $cmd->queryScalar();
        $tree = explode(',', $list);
        $size = count($tree);

        if ($size) {
            $custormer = \common\models\base\Config::findByName('default_custormer_uid');
            $serverid = $custormer ? $custormer->value : 0;
            $last = $size - 1;
            $userid = $tree[$last];
            $server = CsoServer::findOne([
                'user_id' => $userid,
            ]);
            if ($server) {
                $serverid = $server->parent_id;
            }
            if (!$serverid) {
                $serverid = 1;
            }
            $tree[] = $serverid;
        }

        return $tree;
    }

    public function getBranchReward() {
        return $this->hasOne(UserAccountLogs::className(), ['model_id' => 'id'])->andWhere(['model' => 'branch']);
    }

    public function getOrders() {
        return $this->hasMany(MemberMarketLog::className(), ['model_user_id' => 'user_id'])->andWhere(['model' => MemberMarketLog::MODEL_SHOP]);
    }

    public function getOrderCount() {
        return $this->getOrders()->count();
    }

}
